package org.zk.dubbo_consumer.controller;


import lombok.Getter;
import lombok.Setter;
import org.springframework.core.io.ResourceLoader;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.zk.dubbo_consumer.util.*;
import org.zk.entity.Apply;
import org.zk.entity.Teacher;
import org.zk.entity.User;
import org.zk.service.ApplyService;
import org.zk.service.TeacherService;
import org.zk.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 申请表 前端控制器
 * </p>
 *
 * @author Alicelonely
 * @since 2019-12-11
 */
@RestController
@RequestMapping("/apply")
public class ApplyController {

    @Resource
    @Getter
    @Setter
    private final ResourceLoader resourceLoader;

    @Resource
    @Getter
    @Setter
    private TeacherService teacherService;

    @Resource
    @Getter
    @Setter
    private UserService userService;

    @Resource
    @Getter
    @Setter
    private ApplyService applyService;

    //手机号验证码
    private int verificationCode;

    public ApplyController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    //
//    @Value("${web.upload-path}")
//    private String path;

    /**
     * 申请讲师入驻的时候发送验证码（高顺）
     *
     * @param applyPhone
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping("/forgetThePassword")
    public ModelAndView forget(String applyPhone, Model model, HttpServletRequest request) {
        HttpSession session = request.getSession(true);   //用HTTPSession需写这句
            verificationCode = YunPianSend.ypsend(applyPhone); //云片
//        verificationCode = DxUtil.send(applyPhone);      //互亿无线
        System.out.println("verificationCode=" + verificationCode);
        session.setAttribute(applyPhone,verificationCode);
        model.addAttribute("verificationCode", verificationCode);
        return new ModelAndView("user/applyTeacher2");
    }

    /**
     * 申请讲师先往数据库插一部分数据（高顺）
     *
     * @param code
     * @param
     * @param
     * @return
     */
    @RequestMapping("/fileUpload1")
    public Map upload(String code, Apply apply, HttpServletRequest request) {
        HttpSession session = request.getSession(true);   //用HTTPSession需写这句
        session.setAttribute("phone", apply.getApplyPhone());
        String jmphone = DESUtil.encryptBasedDes(apply.getApplyPhone());    //加密后的手机号
        String idcard = DESUtil.encryptBasedDes(apply.getApplyIdcard());      //加密后的身份证号
        String autocode = String.valueOf(verificationCode);     //手机号验证码
        User user = (User) session.getAttribute("user");
        Map map = new HashMap();
        String msg = "";
        if (user != null) {
            if (code.equals(autocode)) {
                apply.setUser(user);
                apply.setApplyPhone(jmphone);
                apply.setApplyIdcard(idcard);
                int result = applyService.insertApplyUser(apply);
                if (result == 1) {
                    msg = "提交成功";
                } else {
                    msg = "提交发生了错误";
                }
            }else {
                msg="验证码输入错误";
            }
        } else {
            msg = "请登录";
        }
        map.put("msg", msg);
        return map;

    }

    @RequestMapping("/toApplyTeacher2")
    public ModelAndView toApplyTeacher2() {
        return new ModelAndView("user/applyTeacher2.html");
    }

    /**
     * @param file 要上传的文件（高顺）
     * @return
     */
    @RequestMapping("fileUpload")
    public ModelAndView upload(@RequestParam("fileName") MultipartFile file, Map<String, Object> map, HttpSession session) {

        // 要上传的目标文件存放路径
        String localPath = "D:\\javaspace\\springboot\\dddddd\\dubbo_pumpkin\\dubbo_consumer\\src\\main\\resources\\static\\image\\gs";
        // 上传成功或者失败的提示
        String msg = "";

        if (FileUtils.upload(file, localPath, file.getOriginalFilename())) {
            // 上传成功，给出页面提示
            msg = "上传成功！";
        } else {
            msg = "上传失败！";
        }
        String applyPhone = (String) session.getAttribute("phone");
        String jmphone = DESUtil.encryptBasedDes(applyPhone);
        Apply apply = new Apply();
        apply.setApplyPhone(jmphone);
        String applyLicense = file.getOriginalFilename();
        apply.setApplyLicense(applyLicense);
        int result = applyService.updataApplyLicense(apply);
        if (result == 1) {
            msg = "上传成功";
            return new ModelAndView("user/applyTeacher3");
        } else {
            msg = "上传失败";
            return new ModelAndView("403");
        }
    }

    /**
     * 审核拒绝的时候跳转拒绝的页面（高顺）
     * @param applyId
     * @param session
     * @return
     */
    @RequestMapping("/toTeacherApplyCause/{applyId}")
    public ModelAndView toTeacherApplyCause(@PathVariable("applyId") int applyId, HttpSession session){
        session.setAttribute("applyId",applyId);
        return new ModelAndView("admin/teacher_apply_cause");
    }
    /**
     * 根据id修改审核状态（拒绝）（高顺）
     * @param apply
     * @return
     */
    @RequestMapping("/updataApplyStateNo")
    public List updataApplyStateNo(Apply apply,HttpSession session){
        List ls=new ArrayList();
        apply.setApplyState("2");
        apply.setApplyId((Integer) session.getAttribute("applyId"));
        int result=applyService.updataApplyStateNo(apply);
        if (result==1){
            session.removeAttribute("applyId");
        }
        return ls;
    }

    /**
     * 根据id修改审核状态（通过）（高顺）
     * @param apply
     * @return
     */

    @RequestMapping("/updataApplyStateYes")
    @ResponseBody
    public Map updataApplyStateYes(Apply apply,String msg){
        apply.setApplyState("1");
        int result=applyService.updataApplyStateYes(apply);
        if (result==1){
            msg="ok";
        }else {
            msg="no";
        }
        Map map=new HashMap();
        map.put("msg",msg);
        return map;

    }

    /**
     * 遍历所有申请讲师的人,也可根据状态去查询（高顺）
     *
     * @param pageNum
     * @param pageSize
     * @param applyRealname
     * @param map
     * @param session
     * @return
     */
    @RequestMapping("/getApplyTeacher")
    public Map getApplyTeacher(int pageNum, int pageSize, String applyRealname,String state, Map map, HttpSession session) {
        map.put("pageSize", pageSize);
        map.put("applyRealname", applyRealname);
        int a = pageSize * (pageNum - 1);
        map.put("a", a);
        List<Apply> applyList = new ArrayList<>();
        int count=0;
        if (state=="" || state==null){
            applyList=applyService.getApplyTeacher(map);
            count = applyService.getApplyContent(map);
        } else if (state.equals("0")) {
            applyList = applyService.selectNoShenHe(map);
            count=applyService.getApplyContentNoShenHe(map);
        } else if (state.equals("1")) {
            applyList = applyService.selectYesTongGuo(map);
            count=applyService.getApplyContentYesTongGuo(map);
        } else if (state.equals("2")){
            applyList = applyService.selectNoTongGuo(map);
            count=applyService.getApplyContentNoTongGuo(map);
        }

        for (Apply apply : applyList) {
            String jiemimPhone = DESUtil.decryptBasedDes(apply.getApplyPhone());
            String jiemiIdCard = DESUtil.decryptBasedDes(apply.getApplyIdcard());
            apply.setApplyPhone(jiemimPhone);
            apply.setApplyIdcard(jiemiIdCard);
        }
        for (int i = 0; i < applyList.size(); i++) {    //把图片存进list

            String ll = applyList.get(i).getApplyLicense();
            applyList.get(i).setApplyLicense("/static/image/gs/" + ll);

            String flag = applyList.get(i).getApplyState();
            if (flag.equals("0")) {
                applyList.get(i).setApplyState("待审核");
            }
            if (flag.equals("1")) {
                applyList.get(i).setApplyState("已审核");
            }
            if (flag.equals("2")) {
                applyList.get(i).setApplyState("不通过");
            }
        }
        int b = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;                              //count/pageSize求多少页
        Map map1 = new HashMap();
        map1.put("apply", applyList);
        map1.put("pageNum", pageNum);
        map1.put("count", count);
        map1.put("ct", b);
        return map1;
    }

    /**
     * 去未通过人的页面（高顺）
     * @return
     */
    @RequestMapping("/toTeacherApplyNoTongGuo")
    public ModelAndView toTeacherApplyNoTongGuo(){
        return new ModelAndView("/admin/teacherApplyNoTongGuo");
    }

    /**
     * 通过后向teacher表加数据（高顺）
     * @param apply
     * @param teacher
     * @return
     */
    @RequestMapping("/insertTeacherYes")
    public Map insertTeacherYes(Apply apply,Teacher teacher){
        Apply apply1=applyService.getAllApplyById(apply.getApplyId());//根据id手动查对应的数据
        User user = userService.selectAllById(apply1.getUser()); //因为在这不能获取session存的user，所以需要手动查
        userService.updateUserSign(user);

        teacher.setUser(user); //teacher表中的大部分数据都是来自user表和apply中
        teacher.setApply(apply1);
        String phone = DESUtil.decryptBasedDes(user.getUserPhone());
        String sub=phone.substring(7,11);
        StringBuffer sb=new StringBuffer();
        String teacherRoom= String.valueOf(sb.append(sub).append(user.getUserId()));
        teacher.setTeacherRoom(teacherRoom);     //主播房间号

        teacher.setUser(user);
        teacher.setApply(apply1);
        teacherService.insertTeacherYes(teacher);

        User user1=new User();  //向teacher表添加成功后修改user表中的状态
        user1.setUserId(user.getUserId());
        user1.setUserSign(1);
        userService.updateUserSign(user1);
        Map map=new HashMap();
        return map;
    }

    /**
     * 在用户进行申请讲师的时候判断用户是否已经正在审核或是已是讲师（高顺）
     * @param apply
     * @param teacher
     * @param
     * @return
     */
    @RequestMapping("/selectHaveOrNoHave")
    public Map selectHaveOrNoHave(Apply apply,Teacher teacher,HttpSession session){
        String applyPhone=DESUtil.encryptBasedDes(apply.getApplyPhone());
        Apply apply1=new Apply();
        apply1.setApplyPhone(applyPhone);
        Apply apply2=applyService.selectHaveOrNoHave(apply1);
        teacher.setTeacherPhone(apply1.getApplyPhone());
        Teacher teacher1=teacherService.selectHaveOrNoHave(teacher);
        User user= (User) session.getAttribute("user");

        String msg="";
        if (user.getUserPhone().equals(apply.getApplyPhone())){
            if (apply2!=null){
                msg="1";      //用户正在审核
            }else if (teacher1!=null){
                msg="2";      //用户已是讲师
            }else {
                msg="3";
            }
        }else {
            msg="4";        //4代表和登录的手机号不一样
        }

        Map map=new HashMap();
        map.put("msg",msg);
        return map;
    }

    /**
     * 根据id删除（高顺）
     * @param applyId
     * @return
     */
    @RequestMapping("/delApplyById")
    public List delApplyById(int applyId){
        List list=new ArrayList();
        applyService.delApplyById(applyId);
        return list;
    }


    //    后台审核教师页面（高顺）
    @ResponseBody
    @RequestMapping("/toTeacherAudit")
    public ModelAndView toTeacherAudit() {
        return new ModelAndView("admin/teacher_audit");
    }

//根据id查教师资格证
    @RequestMapping("/queryPic")
    public ModelAndView queryPic(int applyId) {
        ModelAndView modelAndView = new ModelAndView("/admin/queryLicense");
        String ll = applyService.getApplyById(applyId).getApplyLicense();
        String picPath = "/static/image/gs/" + ll;
        modelAndView.addObject("path", picPath);
        return modelAndView;
    }
}

